<template>
	<view class="page">
		<image src="/static/dingbu.png" class="mine-navbar-bg" :style="{ height: navbarHeight + 'rpx' }"
			mode="aspectFill"></image>
		<u-navbar :title="this.taskID ? '栽培技术审批' : '创建栽培技术'" :autoBack="true" leftIconColor="#fff" bgColor="transparent"
			:titleStyle="{ color: '#fff' }" safeAreaInsetTop placeholder />

		<view class="content">
			<view class="form-card">
				<view class="form-item">
					<text class="label">标题</text>
					<view class="ctrl full">
						<uni-easyinput v-model="form.title" placeholder="请输入" :inputBorder="false" />
					</view>
				</view>

				<view class="form-item">
					<text class="label">视频链接</text>
					<view class="ctrl full">
						<uni-easyinput v-model="form.url" placeholder="请输入" :inputBorder="false" />
					</view>
				</view>

				<!-- <view class="form-item">
					<text class="label">上传时间</text>
					<view class="ctrl full">
						<picker mode="date" :value="form.date" @change="onDateChange">
							<view class="picker-input">
								<text class="date-text">{{ form.date || '请选择日期' }}</text>
								<u-icon name="calendar" color="#29a74d" size="18" />
							</view>
						</picker>
					</view>
				</view> -->

				<view class="form-item top">
					<text class="label">简介</text>
					<view class="ctrl full">
						<uni-easyinput type="textarea" v-model="form.desc" placeholder="请输入" :inputBorder="false"
							:autoHeight="true" />
					</view>
				</view>

				<view class="attach-block">
					<view class="row">
						<text class="label">附件</text>
						<view class="attach-ops">
							<uni-file-picker ref="picker" v-model="files" :limit="9" :auto-upload="false"
								file-mediatype="all" :disable-preview="false" mode="list" @select="onFileSelect"
								@delete="onFileDelete">
								<view class="mini btn-ghost">选择文件</view>
							</uni-file-picker>
							<text class="hint">支持多文件， 最大10MB/个</text>
						</view>
					</view>
					<!-- <view class="row">
						<text class="label"> </text>
						<button class="mini btn-gray" :disabled="!files.length" @click="onDownload">下载文件</button>
					</view> -->
				</view>
			</view>

			<!-- 审批表单控件区域 -->
			<view v-if="formControls.length > 0" class="form-card approval-section">
				<view v-for="control in formControls" :key="control.controlId" class="form-item approval-item">
					<text class="label">{{ control.controlLabel }}</text>
					<view class="w-500">
						<!-- 文本域控件 -->
						<view v-if="control.controlType === 'textarea'">
							<textarea v-model="control.controlValue" :placeholder="`请输入${control.controlLabel}`"
								class="textarea-input" :disabled="!taskID"></textarea>
						</view>

						<!-- 单选框控件 -->
						<view v-else-if="control.controlType === 'radio'">
							<radio-group @change="onApprovalChange(control, $event)">
								<label v-for="(option, optIndex) in control.options" :key="optIndex">
									<radio :value="String(optIndex)"
										:checked="parseInt(control.controlValue) === optIndex" :disabled="!taskID" />
									<text class="radio-text">{{ option }}</text>
								</label>
							</radio-group>
						</view>

						<!-- 其他控件类型 -->
						<view v-else class="approval-other">
							<input v-model="control.controlValue" :placeholder="`请输入${control.controlLabel}`"
								class="input-field" :disabled="!taskID" />
						</view>
					</view>
				</view>
			</view>

			<view class="actions" v-if="!this.taskID">
				<button class="btn primary" @click="onSubmit" :disabled="loading">
					{{ loading ? '提交中...' : '提交' }}
				</button>
				<button class="btn ghost" @click="onDraft" :disabled="loading">
					{{ loading ? '保存中...' : '存草稿' }}
				</button>
				<button class="btn gray" @click="onReset" :disabled="loading">重置</button>
			</view>
			<view @tap="submit()" class="w-690 h-88 br-16 fixed rowsc rowsm fs-36 colfff bg"
				style="bottom: 68rpx;left: 30rpx;" v-if="this.taskID">
				确认
			</view>
		</view>
	</view>
</template>

<script>
import navbarMixin from '@/common/navbarMixin'
import { uploadCultivationPlan } from '@/api/sylin'
import { formDataShow, formDataSave, getSkillInfo } from '@/api/sylin/index'
export default {
	mixins: [navbarMixin],
	data() {
		return {
			form: { title: '', desc: '', url: '' },
			files: [],
			loading: false,
			taskID: '',
			formControls: [] // 存储解析后的表单控件数据
		}
	},
	onLoad() {
		// 接收参数
		this.taskID = this.$route.query.taskID
		this.getTaskData()
		this.getSkillInfo()
	},
	methods: {
		getSkillInfo() {
			getSkillInfo(this.taskID).then(res => {
				this.form.title = res.data.title
				this.form.desc = res.data.content
				this.form.url = res.data.url
			})
		},
		// 提交审批
		submit() {
			// 检查必要参数
			if (!this.taskID) {
				uni.showToast({ title: '任务ID不存在', icon: 'none' })
				return
			}
			
			if (!this.formControls || this.formControls.length === 0) {
				uni.showToast({ title: '没有审批数据', icon: 'none' })
				return
			}
			
			// 参考PC端实现，直接传递对象数组
			const formData = this.formControls.map(control => {
				return {
					controlId: control.controlId,
					controlType: control.controlType,
					controlLable: control.controlLabel, // 注意：PC端用的是controlLable
					controlIsParam: control.controlValue || '', // 使用controlValue作为controlIsParam
					controlValue: control.controlValue || '',
					controlDefault: control.controlDefault || ''
				}
			})
			
			console.log('提交参数:', {
				taskID: this.taskID,
				formData: formData
			})
			
			uni.showLoading({ title: '提交中...' })
			
			formDataSave(this.taskID, formData).then(res => {
				uni.hideLoading()
				console.log('提交响应:', res)
				if (res && res.code === 200) {
					uni.showToast({ title: '提交成功', icon: 'success' })
					// 可以添加页面跳转或其他操作
					setTimeout(() => {
						uni.navigateBack()
					}, 1500)
				} else {
					uni.showToast({ title: res?.msg || '提交失败', icon: 'none' })
				}
			}).catch(err => {
				uni.hideLoading()
				console.error('提交失败:', err)
				uni.showToast({ title: '提交失败: ' + (err.message || '请先签收'), icon: 'none' })
			})
		},
		// 获取审批行数据
		getTaskData() {
			// 只有当taskID存在且有效时才调用API
			if (!this.taskID) {
				console.log('无taskID，跳过获取任务数据')
				return
			}
			formDataShow(this.taskID).then(res => {
				console.log(res, 'res')
				// 处理审批行数据
				if (res && res.code === 200 && res.data && Array.isArray(res.data)) {
					this.parseFormData(res.data)
				}
			}).catch(err => {
				console.error('获取任务数据失败:', err)
				uni.showToast({ title: '获取任务数据失败', icon: 'none' })
			})
		},
		// 解析审批行数据
		parseFormData(formDataArray) {
			try {
				const formControls = []
				
				formDataArray.forEach(item => {
					// 解析格式: "FormProperty_xxx--__!!controlType--__!!controlLabel--__!!controlValue--__!!controlDefault"
					const parts = item.split('--__!!')
					if (parts.length >= 4) {
						const controlId = parts[0] // FormProperty_xxx
						const controlType = parts[1] // textarea, radio, etc.
						const controlLabel = parts[2] // 批注, 审批意见, etc.
						let controlValue = parts[3] // f, i, etc.
						const controlDefault = parts[4] || '' // null, 同意--__--不同意, etc.
						
						// 处理 controlValue 中的 null 值
						if (controlValue === 'null' || controlValue === 'f__!!null') {
							controlValue = ''
						}
						
						const control = {
							controlId,
							controlType,
							controlLabel,
							controlValue,
							controlDefault
						}
						
						// 如果是radio类型，解析选项
						if (controlType === 'radio' && controlDefault) {
							control.options = controlDefault.split('--__--').filter(opt => opt.trim())
						}
						
						formControls.push(control)
					}
				})
				
				console.log('解析后的表单控件:', formControls)
				this.formControls = formControls
				
				// 根据控件类型填充表单
				this.fillFormFromControls(formControls)
				
			} catch (err) {
				console.error('解析审批行数据失败:', err)
			}
		},
		// 根据控件数据填充表单
		fillFormFromControls(controls) {
			controls.forEach(control => {
				switch (control.controlLabel) {
					case '批注':
						// 如果有批注字段，可以存储到备注中
						this.form.remark = control.controlValue
						break
					case '审批意见':
						// 审批意见通常是radio类型
						if (control.controlType === 'radio') {
							this.form.approvalResult = control.controlValue
						}
						break
					// 可以根据实际需要添加更多字段映射
				}
			})
		},
		// 审批控件值改变事件
		onApprovalChange(control, event) {
			const selectedValue = event.detail.value
			// 确保存储的是字符串类型，与后端数据格式一致
			control.controlValue = String(selectedValue)
			console.log('审批控件值改变:', control.controlLabel, selectedValue)
		},
		// 获取控件值（用于显示当前选中的值）
		getControlValue(control) {
			// 处理空值情况
			if (!control.controlValue || control.controlValue === 'null' || control.controlValue === 'f__!!null') {
				return ''
			}
			
			if (control.controlType === 'radio') {
				// 对于radio类型，返回选中的选项文本
				const selectedIndex = parseInt(control.controlValue)
				if (control.options && control.options[selectedIndex]) {
					return control.options[selectedIndex]
				}
				return control.controlValue
			}
			return control.controlValue
		},
		onFileSelect(e){
			const MAX = 10 * 1024 * 1024
			const keep = (e?.tempFiles || []).filter(f => (f?.size || 0) <= MAX)
			const over = (e?.tempFiles || []).length - keep.length
			if (over>0) uni.showToast({ title: '有文件超过10MB已忽略', icon: 'none' })
			if (keep.length) this.files = [...(this.files||[]), ...keep]
		},
		onFileDelete(e){
			if (typeof e?.index === 'number' && this.files?.length) {
				this.files.splice(e.index,1); this.files=[...this.files]
			}
		},
		async onDownload(){
			if (!this.files?.length) return uni.showToast({ title:'暂无可下载文件', icon:'none' })
			const first = this.files[0]
			const url = first.url || first.path || first.tempFilePath
			if (!url) return uni.showToast({ title:'下载失败', icon:'none' })
			try{
				const res = await new Promise(r=>uni.downloadFile({ url, success:r, fail:r }))
				const fp = res?.tempFilePath
				fp ? uni.openDocument({ filePath: fp }) : uni.showToast({ title:'下载失败', icon:'none' })
			}catch{ uni.showToast({ title:'下载失败', icon:'none' }) }
		},
		async onSubmit() {
			// 验证表单
			if (!this.form.title.trim()) {
				uni.showToast({ title: '请输入标题', icon: 'none' })
				return
			}
			if (!this.form.desc.trim()) {
				uni.showToast({ title: '请输入简介', icon: 'none' })
				return
			}
			if (!this.files.length) {
				uni.showToast({ title: '请选择文件', icon: 'none' })
				return
			}
			if (!this.form.url.trim()) {
				uni.showToast({ title: '请输入视频链接', icon: 'none' })
				return
			}

			this.loading = true
			
			try {
				// 构建请求数据 - 根据接口参数调整
				const data = {
					name: this.form.title.trim(), // 标题
					content: this.form.desc.trim(), // 简介
					url: this.form.url.trim(), // 视频链接 - 暂时为空，如果需要可以添加视频上传功能
					file: this.files.map(f => f.url || f.path || f.tempFilePath).join(','), // 文件地址
					postFlag: 1 // 提交标识 - 1表示提交
				}
				
				console.log('提交数据:', data)
				const response = await uploadCultivationPlan(data)
				console.log('提交结果:', response)
				
				if (response && response.code === 200) {
					uni.showToast({ title: '提交成功', icon: 'success' })
					this.onReset()
				} else {
					uni.showToast({ title: response?.msg || '提交失败', icon: 'none' })
				}
			} catch (error) {
				console.error('提交失败:', error)
				uni.showToast({ title: '网络错误，请重试', icon: 'none' })
			} finally {
				this.loading = false
			}
		},

		async onDraft() {
			// 验证表单
			if (!this.form.title.trim()) {
				uni.showToast({ title: '请输入标题', icon: 'none' })
				return
			}
			if (!this.form.desc.trim()) {
				uni.showToast({ title: '请输入简介', icon: 'none' })
				return
			}
			if (!this.form.url.trim()) {
				uni.showToast({ title: '请输入视频链接', icon: 'none' })
				return
			}
			this.loading = true
			
			try {
				// 构建请求数据 - 根据接口参数调整
				const data = {
					name: this.form.title.trim(), // 标题
					content: this.form.desc.trim(), // 简介
					url: this.form.url.trim(), // 视频链接 - 暂时为空
					file: this.files.map(f => f.url || f.path || f.tempFilePath).join(','), // 文件地址
					postFlag: 0 // 提交标识 - 0表示暂存
				}
				
				console.log('草稿数据:', data)
				const response = await uploadCultivationPlan(data)
				console.log('草稿结果:', response)
				
				if (response && response.code === 200) {
					uni.showToast({ title: '草稿已保存', icon: 'success' })
					this.onReset()
				} else {
					uni.showToast({ title: response?.msg || '保存草稿失败', icon: 'none' })
				}
			} catch (error) {
				console.error('保存草稿失败:', error)
				uni.showToast({ title: '网络错误，请重试', icon: 'none' })
			} finally {
				this.loading = false
			}
		},

		onReset() {
			this.form = { title: '', desc: '' }
			this.files = []
		},

		onCancel(){ uni.navigateBack({ delta:1 }) }
	}
}
</script>

<style lang="scss" scoped>
$brand: #29a74d;
$brand-weak: #e9f7ee;
$brand-border: #cfe9db;
$brand-strong: #239243;

.mine-navbar-bg { position: fixed; top: 0; left: 0; width: 100%;  z-index: 2; }
.page { background: #f6f7fb; min-height: 100vh; }
.content { padding: 24rpx; }

.form-card { background: #fff; border: 1rpx solid #eef2f7; border-radius: 22rpx; padding: 12rpx 18rpx; box-shadow: 0 10rpx 24rpx rgba(12,18,28,.06); }
.form-item { display: flex; align-items: center; padding: 18rpx 8rpx; }
.form-item + .form-item { border-top: 1rpx dashed #eef2f7; }
.form-item.top { align-items: flex-start; }

.label { width: 200rpx; color: #374151; font-size: 28rpx; line-height: 72rpx; }
.ctrl { flex: 1; display: flex; align-items: center; }
.ctrl.full { width: 100%; }

::v-deep .uni-easyinput__content { background: $brand-weak; border-radius: 14rpx !important; min-height: 72rpx;}
::v-deep .uni-easyinput__content-textarea { background: $brand-weak; border-radius: 14rpx; min-height: 72rpx; padding: 16rpx 20rpx; border: 1rpx solid $brand-border; }
::v-deep .uni-easyinput__placeholder-class { color: #9ca3af; }

.picker-input { height: 72rpx; border: 1rpx solid $brand-border; border-radius: 14rpx; padding: 0 20rpx; display: flex; align-items: center; justify-content: space-between; background: $brand-weak; color: #111827; }
.date-text { color: #111827; }

.attach-block { padding: 12rpx 8rpx 4rpx; }
.attach-block .row { display: flex; align-items: center; padding: 12rpx 0; }
.attach-ops { display: flex; align-items: center; gap: 16rpx; }
.hint { color: #6b7280; font-size: 22rpx; }

.mini { height: 56rpx; line-height: 56rpx; border-radius: 12rpx; padding: 0 28rpx; font-size: 26rpx; min-width: 168rpx; display: inline-flex; align-items: center; justify-content: center; white-space: nowrap; overflow: visible; }
.btn-ghost { background: #fff; color: $brand-strong; box-shadow: inset 0 0 0 1rpx $brand-border; }
.btn-gray { background: #e5e7eb; color: #374151; border: none; }

.actions { display: grid; grid-template-columns: repeat(3, 1fr); gap: 18rpx; padding: 26rpx 12rpx; }
.btn { height: 72rpx; line-height: 72rpx; border-radius: 14rpx; font-size: 28rpx; border: none; }
.btn.primary { background: linear-gradient(90deg, lighten($brand, 2%), $brand-strong); color: #fff; box-shadow: 0 6rpx 14rpx rgba(37,154,68,.22); }
.btn.ghost { background: #fff; color: $brand-strong; box-shadow: inset 0 0 0 1rpx $brand-border; }
.btn.gray { background: #e5e7eb; color: #374151; }

.btn:disabled { opacity: 0.6; cursor: not-allowed; }

/* 审批表单样式 */
.approval-section {
	margin-top: 24rpx;
}
.approval-item {
	border-top: 1rpx dashed #eef2f7;
}

.approval-item:first-child {
	border-top: none;
}

.textarea-input {
	width: 100%;
	min-height: 120rpx;
	padding: 16rpx;
	border: 1rpx solid $brand-border;
	border-radius: 14rpx;
	background: $brand-weak;
	font-size: 28rpx;
	color: #111827;
	resize: none;
}

.textarea-input:disabled {
	background: #f9fafb;
	color: #9ca3af;
}

.radio-item {
	display: flex;
	align-items: center;
	margin-bottom: 16rpx;
	padding: 12rpx 16rpx;
	border-radius: 12rpx;
	background: #f9fafb;
	border: 1rpx solid #e5e7eb;
}

.radio-item:last-child {
	margin-bottom: 0;
}

.radio-text {
	margin-left: 12rpx;
	margin-right: 20rpx;
	font-size: 28rpx;
	color: #374151;
}

.radio-item:disabled {
	opacity: 0.6;
}

.approval-other {
	width: 100%;
}

.input-field {
	width: 100%;
	height: 72rpx;
	padding: 0 20rpx;
	border: 1rpx solid $brand-border;
	border-radius: 14rpx;
	background: $brand-weak;
	font-size: 28rpx;
	color: #111827;
}

.input-field:disabled {
	background: #f9fafb;
	color: #9ca3af;
}

.w-500 {
	width: 500rpx;
}
</style>
